# Chapter 2

# Working with Larger Programs and Variables

CONTENTS

- JavaScript Language Structure
  - Statements
  - Functions
  - Variables
  - Expressions
  - Objects, Properties, and Methods
- Using Comments
- Programs and Applications
- Data Types and Variables
  - Integers
  - Floating-Point Numbers
  - Boolean Values
  - Strings
  - Special Characters
- Creating an Array
- Working with Numbers and Text
- Naming and Declaring Variables
  - Rules for JavaScript Variable Names
- Assigning Values to Variables
- Variable Declarations and Scope
- Declaring Variables
- Using Expressions and Operators
  - Assignment Operators
  - Arithmetic Operators
- Incrementing and Decrementing Variables
  - String Operators
  - Logical Operators
  - Bitwise Operators
  - Comparison Operators
  - Understanding Operator Precedence
- Using Variables in Expressions
- Converting and Evaluating Variables and Expressions
  - The `parseInt` Function
  - The `parseFloat` Function
  - The `eval` Function
- Workshop Wrap-Up
  - Next Steps
  - Q&A

Without a way of storing data and using it repeatedly, a programming language isn't much better than a pocket calculator. In this chapter, you explore the types of data you can use in JavaScript, and how to define and use variables to store data. You'll also learn a bit about the structure of the JavaScript language.

## JavaScript Language Structure

JavaScript has a simple, relaxed structure. You can include a single line of JavaScript in an HTML document, and it will act as a JavaScript program in itself. No specific statements are required to begin or end a JavaScript script, except for the `<SCRIPT>` and `</SCRIPT>` tags in HTML. For example, this is a simple JavaScript program to print a message:

>     <SCRIPT LANGUAGE="JavaScript">
>     document.write("The eagle has landed. The fat man walks alone.");
>     </SCRIPT>

This script includes a single JavaScript statement. The `document.write()` command is actually part of the `document` object, which you will learn about in detail later; however, you don't need to understand objects to know that this statement simply prints the text, as if it were part of the HTML.

A wide variety of statements are available to perform different types of tasks. A statement can also assign a value to a variable, as you'll see later in this chapter.

Statements or functions that require a parameter, such as `document.write()` in the last example, use parentheses to surround their parameters. If more than one parameter is required, they are separated by commas. For example, this statement sends three numbers to a function called `total`:

>     result = total(12,36,14.5);

Notice the semicolon at the end of the example statement. This is a common feature of many languages, such as C and Java, to indicate the end of a statement. However, JavaScript isn't as picky as those languages; you can leave out the semicolons if you desire. You may want to include them for clarity, or to avoid developing a bad habit if you routinely program in C, Java, or Perl.

The final punctuation marks you will need for JavaScript programs are the left and right braces: `{` and `}`. If you're familiar with C or Perl, you know that those languages use brackets to enclose blocks of statements, and that all statements must be inside a set of brackets. Once again, JavaScript isn't as strict as other languages. The only time braces are needed is when you are defining a block of statements for a specific purpose, such as a function.

Note
JavaScript keywords, function and object names, and variable names are case-sensitive. Be sure you use the correct combination of upper- and lowercase when entering JavaScript statements.

Next, let's take a look at the various components that can be included in a JavaScript program. You will learn about these in detail in this chapter and in Chapters 3, "Working with Objects and Events," and 4, "Using Built-In Objects and Custom Objects."

### Statements

Statements are simply commands that perform a certain purpose. Several statements are built into JavaScript; these are used to test variables, control the flow of the program, and perform actions.

The term statement is also used to refer to any line of JavaScript code. For example, the `document.write()` statement used in the examples is technically an object method, which you'll explore in detail in Chapter 3.

### Functions

A function accepts parameters and returns a value. You explore three built-in functions in the section titled Converting and Evaluating Variables and Expressions later in this chapter:

- `parseInt` converts strings to integers.
- `parseFloat` converts strings to floating-point numbers.
- `eval` evaluates JavaScript expressions.

You can also define your own functions with the `function` keyword. This example defines a very simple function that adds two numbers:

>     function Add(a,b){
>        var result = a + b;
>        return result;
>     }

To use a function, you simply include the function's name, followed by the parameters in parentheses. For example, here is a simple script that uses the `Add()` function to print a result:

>     var test = Add(2,4);
>     document.write("Two plus four equals:",test);

### Variables

A variable is simply a name given to a value. Variables can be given different values throughout the course of a JavaScript program. In the previous example, a variable called `test` is used to store the result returned by the `Add()` function. You learn about variables in detail in the section titled Data Types and Variables later in this chapter.

### Expressions

An expression is something that JavaScript interprets before using it in a statement. For example, this statement assigns a number to the variable `total`, using an expression:

>     total = result1 + result2;

The expression `result1 + result2` is interpreted; in this case, the values are simply added together. This value is then used as the value to assign to the `total` variable. Along with mathematical expressions, expressions can include function results and conditional expressions (explained in Chapter 3).

### Objects, Properties, and Methods

Recall from Chapter 1 "Creating Simple JavaScript Programs," that JavaScript is an object-oriented language. This means that it supports objects. Objects are custom data types that combine data with functions. An object includes properties, which hold the data. In addition, it can include methods, functions to act on the data. You'll learn about objects in detail in Chapter 3.

## Using Comments

A final element you can include in a JavaScript program is a comment. These are items of text that can be included for your information, or for others who might try to understand the script. Comments are ignored by the JavaScript interpreter.

JavaScript supports two types of comments:

- A single-line comment begins with two slashes (`//`) and ends at the end of the line.
- A multiple-line comment begins with the `/*` delimiter and ends with the `*/` delimiter. This type of comment can include any number of lines. These work like the comments in the C language.

You can use whichever type of comment is the most convenient. The `/*` and `*/` comments are useful for "commenting out" a block of JavaScript code to prevent it from executing temporarily. Single-line comments are handy to provide descriptions of particular lines of code. The following short JavaScript example includes both types of comments:

>     //function to return total number of cars
>     function total(compact, subcompact, luxury) {
>        var temp = compact + subcompact + luxury;
>        // we don't want to print right now, so these are commented out.
>        /*document.write("Compacts: ",compact, " Subcompacts: ", subcompact);
>        document.write("Luxury cars: ",luxury, "\n");
>        document.write("Total number of cars: ", temp);*/
>        //above lines are commented out; nothing will be printed.
>        return temp;
>     }

As you can see, comments can help make your JavaScript code readable-and in some cases, they can make it more confusing. It's generally a good idea to avoid making excessive comments, but rather to label major sections of the program and statements that may be confusing.

Pay special attention to the comments in listings in this book; they are used to make some statements more clear, and occasionally to illustrate a point in the text.

Note
Do not confuse JavaScript comments with HTML comments. You can use HTML comments to hide JavaScript commands from non-JavaScript browsers, and they cannot be used within the script. JavaScript comments are part of the script, and they can be used only between the `<SCRIPT>` tags.

## Programs and Applications

The concept of just what a program is can be confusing in JavaScript, because it's tightly integrated with HTML-two languages in the same file. Programs and applications are not technical JavaScript terms, but I'll define them here, because they are used frequently throughout this book:

- A JavaScript program consists of all of the functions, event handlers, and variable declarations included in a single HTML file. These might not execute in the order they are defined, but the browser reads and interprets them all at the same time.
- Consider a JavaScript application to be a set of HTML files and scripts that work together to form a useful purpose. A complete application might involve several JavaScript programs in several different HTML files, and may even include additional functionality through different languages, such as CGI or Java.

## Data Types and Variables

One of the most important features of a programming language is the capability of working with data. JavaScript includes flexible support for most types of data with which you will need to work.

You can use data in a JavaScript program in two ways:

- As a literal or constant value, which is included directly in the JavaScript code. For example, `54`, `6.17`, and `"This"` are all literal values.
- As a variable. As mentioned earlier in this chapter, variables are named containers that can hold a value. You can assign them different values during the course of the program. Variable names might include `total`, `tax_amt`, or `data1`.

JavaScript includes support for relatively few types of data, but you can use these to create other types. In fact, using JavaScript's object-oriented features, you can create a wide variety of custom types.

The four fundamental data types used in JavaScript are the following:

- Numbers, such as `3`, `25`, or `1.4142138`. JavaScript supports both integers and floating-point numbers.
- Boolean, or logical values. These can have one of two values: `true` or `false`.
- Strings, such as `"This is a string"`. These consist of one or more characters of text.
- The null value, represented by the keyword `null`. This is the value of an undefined variable.

Some programming languages, such as C and Java, are strongly typed. This means that variables can hold a very specific type of value. You have to declare the type of data a variable can hold when you define it, and you must use conversion functions when you wish to change a variable's type. This works fine for in-depth, structured programming, but isn't really ideal for the quick jobs for which JavaScript can be used.

By contrast, JavaScript is a loosely typed language. This means that when you declare a variable, you don't have to define its type. You can store any allowable type of data in a variable. Conversions between different types of data happen automatically.

Note
Another example of a loosely typed language is Perl, a popular choice for CGI scripts and other Internet applications. Perl variables, like JavaScript, can hold different types of data.

Because JavaScript is loosely typed, you don't need to give much thought to the type of data a variable will hold. Nevertheless, there are special considerations for each type of data, which are discussed in detail in the following sections.

### Integers

An integer is simply a number that does not include a decimal. Integers in JavaScript can be only positive numbers. You can use an integer as a literal in JavaScript simply by including the number. For example, this statement prints the number `47`:

>     document.write(47);

JavaScript considers any number without a leading zero to be a decimal (base 10) number. You can also use data in hexadecimal (base 16) and octal (base 8). Here is a summary of the syntax you use to specify different types of numbers with examples:

- Decimal: no leading zero (`57`, `5000`)
- Hexadecimal: prefix with `0x` (`0x56`, `0xFE`)
- Octal: leading `0` (`045`, `013`)

You can include integers in your programs in whichever base is convenient. For example, 42, 052, and 0x2A are all different ways of listing the decimal number 42. Because you probably think best in base 10, decimal numbers are the easiest to use in most cases; however, there are some situations when another format is more convenient. For example, the color codes used to specify background and text colors in an HTML page are usually given in hexadecimal.

Note
Base 10 numbers can also use decimal fractions, as you will learn later. Hexadecimal and octal numbers are limited to integer values.

### Floating-Point Numbers

You can also use floating-point decimal numbers in your JavaScript programs. These can be used to represent just about any number conveniently. A simple floating-point value consists of an integer followed by a decimal point and a fractional value, such as 2.01.

Unlike integers, floating-point values can be either positive or negative. You can specify negative values for floating-point numbers by adding the negative sign to the beginning of the number, as in `-3.1`. Any number without a negative sign is assumed to be positive.

You can also use a form of scientific notation to refer to floating-point numbers. This makes it easy to specify very large numbers. To use this notation, you include the letter E (either upper- or lowercase) followed by the exponent, either positive or negative.

Positive exponents move the decimal point to the right or make the number larger; negative exponents make the number smaller. Here are a few examples of exponent notation and the decimal numbers they represent:

- 1E6: One million (1,000,000)
- 1.5E9: 1.5 billion (1,500,000,000)
- 25E-2: One-quarter (.25)
- 1E-6: One-millionth (.000001)
- 4.56E5: 456,000

### Boolean Values

Boolean values are the simplest data type. They can contain one of two values: `true` or `false`. Because they can represent an on/off or 1/0 state, these are sometimes called binary values.

Boolean values are most commonly used as flags; variables that indicate whether a condition is true or not. For example, you might set a Boolean variable called `complete` to `true` to indicate that the user has completed all the needed information in a form. You can then easily check this value and act on it later.

Note
You can use the numbers `0` and `1` as synonyms for `false` and `true` in many cases in JavaScript; however, it's best to treat Boolean values as strictly Boolean.

### Strings

Another important type of value you can work with in a JavaScript program is a string. Strings are simply groups of characters, such as `"Hello"` or `"I am a jelly doughnut."`.

You can include strings as literals in JavaScript by enclosing them in double or single quotation marks. Here are some examples of values that JavaScript will treat as strings:

- `"This is a string."`
- `'A'`
- `'25 pounds'`
- `"200"`

You can use the two types of quotes interchangeably. However, you must use the same type of quote to end the string that you used to begin it.

Tip
HTML uses double quotation marks to indicate values for some tags. Because you will be using JavaScript within HTML documents, and especially in event handlers, you may want to get into the habit of using single quotation marks within JavaScript statements. This will avoid conflicts with the HTML codes.

### Special Characters

Along with alphanumeric characters, you can use a variety of special characters in JavaScript strings. These include carriage returns, tabs, and other nonprintable characters.

To use one of these special characters, include a backslash (`\`) followed by the code for that character. The codes are as follows:

- `\a`: Alert (bell) character (produces a bell sound)
- `\b`: Backspace character (moves the cursor back one character)
- `\f`: Form-feed character (indicates a new page on a printer)
- `\n`: New line character (indicates a new line of text)
- `\r`: Carriage return character (moves the cursor to the beginning of the line)
- `\t`: Tab character (advances the cursor to the next tab stop)

You can include special characters directly in a string. For example, the following statement prints out three separate lines of text:

>     document.write(" this is line 1\n this is line 2\n this is line 3");

Depending on what you're using the string for, some of these characters may or may not have a meaning. For example, this line will only work in a predefined portion of the HTML page. Tab and form-feed characters will not affect HTML output to the browser, but they may be useful for other applications.

Another use for the backslash is to include quotation marks within a string. This is known as escaping a character. For example, the following statement won't work, because it uses quotation marks incorrectly:

>     document.write("Jane said, "Have you seen my wig around?"");

This is invalid because quotation marks can be used only at the beginning and end of the string. You can escape the quotation marks within the string with the backslash character to make a correct statement:

>     document.write("Jane said, \"Have you seen my wig around?\"");

The escaped quotation marks are considered as part of the literal string, so this will print the correct result, including quotation marks. You can also use the backslash character twice to include an actual backslash character in a string:

>     document.write("The DOS files are in the C:\\DOS\\FILES directory.");

Tip
Single quotation marks, double quotation marks, and backslashes are the only characters you need to escape with the backslash character. You can include any other punctuation character inside the quotation marks, and it will be considered part of the string.

## Creating an Array

Many languages support arrays-numbered sets of variables. For example, scores for 20 different students might be stored in a `scores` array. You could then refer to `scores[1]` for the first student's score, `scores[5]` for the fifth student, and so on. This makes it easy to define a large number of variables without having to give each one a name. The number in the brackets is called an index into the array.

JavaScript does not support arrays as variables. Instead, they are handled as objects. You can create an array by using the `Array` object. As an example, this statement creates an array called `scores` with 20 values:

>     scores = new Array(20);

Once you define the array, you can access its elements by using brackets to indicate the index. For example, you can assign values for the first and tenth scores with these statements:

>     scores[0] = 50;
>     scores[9] = 85;

As you learn more about JavaScript objects, you'll learn that you can create much more complicated structures than mere arrays. In the meantime, you can use arrays to store any numbered set of values.

Tip
In the previous example, notice that the first student's score is referred to as `scores[0]`. As in many other computer languages, JavaScript array indices begin with `0`. A five-element array would have indices from `0` to `4`.

## Working with Numbers and Text

To get an idea of how data typing works in JavaScript, let's look at some examples of using numbers and text in variables. To begin, consider these statements:

>     total = 22;
>     description = " large polar bears";

These variables are now declared; `total` is an integer, and `description` is a string. Suppose this statement happened next:

>     total += .025;

This adds a fraction to `total`. The type for `total` is changed to floating-point, and its value is now `22.025`. Now add to `total` again:

>     total += .975;

This brings `total` up to `23`-an integer once again.

>     total = total + description;

Now things get a bit tricky. You might think this statement would cause an error-not in JavaScript. The values are automatically converted to match. They are treated as strings, so instead of addition, concatenation (combining strings) is used.

As a result, `total` is now a string variable, and its value is `"23 large polar bears"`. You should now see how easy JavaScript is to work with-much easier than actual polar bears.

## Naming and Declaring Variables

By now, you should have a good understanding of what variables are for, and what types of data you can store in them. Next, let's take a quick look at the rules you must follow when using variables: how to name them, and how and where to declare them.

### Rules for JavaScript Variable Names

As mentioned earlier in this chapter, each variable has a name. In technical terms, JavaScript calls the variable name an identifier. There are specific rules you must follow when choosing a variable name:

- Variable names can include letters of the alphabet, both upper- and lowercase. They can also include the digits 0-9 and the underscore (_) character.
- Variable names cannot include spaces or any other punctuation character.
- The first character of the variable name must be either a letter or the underscore character.
- Variable names are case-sensitive; `totalnum`, `Totalnum`, and `TotalNum` are separate variable names.
- There is no official limit on the length of variable names, but they must fit within one line.

Using these rules, the following are examples of valid variable names:

>     total_number_of_students
>     LastInvoiceNumber
>     temp1
>     a
>     _var39

Obviously, it's possible to use friendly, easy-to-read names or completely cryptic ones. Do yourself a favor: use longer, friendly names whenever possible. One exception is temporary variables that are used in a small section of code; one-letter names or single words work well for these and save a bit of typing.

## Assigning Values to Variables

You've already seen several examples of assigning a value to a variable. The syntax for an assignment is simply an equal sign (`=`). For example, the following statement assigns the value `18` to the variable `wheels`:

>     wheels = 18;

This is a good time to explain more about the loosely typed nature of JavaScript. After assigning the integer value `18` to the `wheels` variable, the following assignment is perfectly valid:

>     wheels = "round rolling things";

JavaScript now converts the `wheels` variable to a string type, and it becomes valid in expressions that require a string. Although this is one of JavaScript's greatest strengths, it can also be a weakness. For example, later in your program you might have the following statement:

>     document.write("The vehicle has ",wheels, " wheels.\n");

In this case, a statement that would have produced sensible output with one value now produces nonsense. Even worse, consider the following statement:

>     total_wheels = wheels * NumberOfVehicles;

If the `wheels` variable has been assigned a string, you now have a statement that will cause an error, or at least cause the data to be corrupt.

Although you can probably remember which type to use in your variables, don't count on the user to remember. Because situations like this can happen, you'll need to be careful any time the user enters a value.

## Variable Declarations and Scope

In some languages, you must declare each variable you will use. JavaScript does not require this; the first time you assign a value to a variable, it is automatically declared. You may also need to use the `var` keyword to declare a variable, depending on where you will use it.

Any variable in JavaScript has a scope-a section of code in which it is valid. There are generally two types of scope possible in JavaScript:

- A variable declared within a function with the `var` keyword is local to that function; other functions cannot access it. Variables used to store the function's parameters are also local to the function.
- A variable declared outside a function, or without the `var` keyword in a function, is global; all JavaScript statements in the current HTML or script file can access the value.

This means that if you define a variable called `temp` with the `var` keyword in a function, it can't be accessed by other functions. In fact, another function can declare a local variable with the same name, and it will have its own separate storage area. There will be no conflict between the two `temp` variables.

By using the `var` keyword, you can make it clear that you are declaring a variable-either local (within a function) or global (outside a function). The following example declares a variable called `keys` and sets its initial value to `88`:

>     var keys=88;

In many cases, local variables are convenient-such as for holding parameters passed to a function or calculating a result to be displayed. You will want to declare global variables for values that several functions within the HTML file will use.

A global variable's declaration must occur in the HTML file before any statements that use it. The most common place to declare global variables is in the `<HEAD>` section of the HTML document. This ensures that they'll come first, and also conveniently hides the JavaScript code from non-JavaScript browsers.

## Declaring Variables

To make it clear how to use variables and scope, let's look at a few examples. First of all, an important thing to remember is that a variable is declared the first time you use it. Consider the example in Listing 2.1.

> Listing 2.1. (DECLARE.htm) Variable declarations.

>     <HTML>
>     <HEAD><TITLE>Variable Declarations</TITLE>
>     <SCRIPT LANGUAGE="JavaScript">
>     var teeth = 30;
>     var arms = 2;
>     legs = 2;
>     function init() {
>        teeth = teeth - 4;
>        var heads = 1;
>        eyes = heads * 2;
>     }
>     </SCRIPT>
>     </HEAD>
>     <BODY>
>     Text here.
>     </BODY>

This example includes quite a few variable declarations. (In fact, it does little else.) Let's take a look at each one:

- `teeth` and `arms` are declared as global in the header with the `var` keyword.
- `legs` does not use the `var` keyword, but is still declared as global because the declaration is outside any function.
- `heads` is declared as local by using the `var` keyword within the `init` function.
- `eyes` is declared without `var`, so it is global, although declared within the `init` function.

This should give you a good understanding of which variables will be local and global. Be sure to use the correct syntax with your variables; incorrect syntax is one of the most common JavaScript programming errors.

## Using Expressions and Operators

You can combine variables and literal values to form a complex expression. The tools you use to create an expression are operators. A simple example of an operator is the plus sign in the expression `students + 1`. JavaScript supports the following types of operators:

- Assignment operators are used to assign a value to a variable, or change its current value.
- Arithmetic operators are used to perform addition, subtraction, and other math on numeric literals or variables.
- String operators are used to manipulate string values.
- Logical operators deal with Boolean values, and are mainly used for testing conditions.
- Bitwise operators are used to manipulate individual bits of a numeric value in a Boolean fashion.
- Comparison operators are used to test the relationship between two numeric values.

You'll learn about the various operators of each type provided by JavaScript in the next sections. You will also explore operator precedence, the system used to determine which operation will be performed first in a complex expression.

### Assignment Operators

One assignment operator has already been used in this chapter: the equal sign (`=`). This is the simplest assignment operator. It assigns the value (or expression) to the right of the equal sign to the variable on the left. Here are some examples:

- `test_score = 199` assigns the number `199` to the variable `test_score`.
- `a = b + 1` adds `1` to variable `b` and stores the result in `a`.
- `a = Results(12)` sends the number `12` to a function called `Results()` and stores the returned value in `a`.
- `a = a + 1` adds `1` to the variable `a` and stores the new value in `a`.

In the last example, an operation is performed on a variable and stored in the same variable. Because this is a common task, there are several assignment operators that make it easier:

- `+=` adds the number on the right to the variable on the left.
- `-=` subtracts the number on the right from the variable on the left.
- `*=` multiplies the variable by the number on the right.
- `/=` divides the variable by the number on the right.
- `%=` uses the modulo operator, described in the next section.

The statement used as an example earlier, `a = a+1`, thus can be written in a shorter form: `a += 1`. Addition is a particularly common use for these operators, because you routinely need to add one (or another number) to a counter variable. Here are a few final examples:

- `count += 1` adds `1` to, or increments, the `count` variable.
- `a *= b` multiplies `a` by `b` and stores the result in `a`.
- `a /= 2` divides the value of `a` by `2` and stores the result in `a`.

There are also several assignment operators for bitwise operations, described in the section Bitwise Operators, later in this chapter.

### Arithmetic Operators

Arithmetic operators are used to perform mathematical operations on variables and literals. You're already familiar with the basic arithmetic operators: addition (`+`), subtraction (`-`), multiplication (`*`), and division (`/`). These work the way you would expect them to, and each has an equivalent assignment operator. There are several other operators, explained in the next sections.

#### The Modulo Operator

You may have encountered the modulo (`%`) operator in a different programming language; it works the same way in JavaScript. In case you haven't seen it before, let's look at the following example:

>     b = a % 2;

This would be read as "b equals a modulo 2." Technically speaking, modulo is the remainder when two numbers are divided. Thus, the example could be explained as "the remainder when you divide x by 2." Here are a few literal examples:

- 100 % 2 = 0 (2 divides into 100 evenly; there is no remainder)
- 100 % 3 = 1 (100 divided by 3 is 33, with a remainder of 1)
- 20 % 7 = 6 (20 divided by 7 is 2, with a remainder of 6)

Right now the modulo operator may seem useless, but you'll run into many uses for it throughout this book. Just to prove that it's worth something, note that the result of the first example is `0`. If a modulo operation returns `0`, this means the number is evenly divisible, so this is an easy way to test whether a number is even or odd, or whether it is divisible by some other number. This example:

>     If (a % 2 == 0) document.write("a is an even number.\n");

also uses a comparison operator, which is described later in this section.

#### The Negation Operator

You've already seen the negation operator used with numbers. The minus sign at the beginning of the number `-3.11` indicates that the number is negative. You can also use this unary negation operator with variables. For example, look at this statement:

>     temp = -temp;

This replaces the value of `temp` with its negative equivalent, or complement. If `temp` had a value of `17`, its new value would be `-17`. Negating a number that is already negative results in a positive number. If the value of `temp` was `-25`, the new value would be `25`.

## Incrementing and Decrementing Variables

Recall from the section on assignment operators that short versions exist for commands that operate on one variable and store the result in the same variable. For example, the following statements are equivalent:

>     a = a + 1;
>     a += 1;

Both add `1` to the value of `a`, and store the result in `a`. Because it's very common to add 1 to the value of a number, or subtract 1 from its value, JavaScript provides an even shorter method of doing so with the increment and decrement operators:

- Increment (`++`) adds 1 to the variable's value.
- Decrement (`--`) subtracts 1 from the variable's value.

Thus, the statements could be written in an even shorter way:

>     a++;

The increment and decrement operators can be used as either a prefix or a postfix; in other words, they can be before or after the variable name, respectively. For example, both of these statements decrement the variable `count`:

>     count--;
>     --count;

The difference between these two methods is when the increment or decrement operation actually happens. If you use prefix notation, the variable is incremented before it is used in an expression; if you use postfix notation, it is incremented after. This example should help make this clear:

>     total = count++;

This assigns the value of `count` to the variable `total`, and then increments the count. For example, if `count` is `25` before this statement, `total` will receive a value of `25`, and `count` will then be incremented to `26`. Now look what happens when you use a prefix:

>     total = ++count;

In this case, `count` is incremented before using it in the expression. If `count` starts with a value of `25`, it will be incremented to `26`, and `total` receives a value of `26`. Obviously, you need to choose carefully which method to use, depending on when you need the incrementing or decrementing to happen.

### String Operators

There is only one dedicated string operator in JavaScript: the concatenation operator (`+`). This takes the string on the right and tacks it onto the string on the left. Here are three examples:

>     text = header + " and so forth.";
>     sentence = subject + predicate;
>     chars = chars + "R";

In the first example, if the `header` string variable contained the text `"This is a test"`, the value assigned to `text` would be "This is a test and so forth." This makes it easy to combine strings.

The last example uses the same variable on both sides of the equal sign. Like arithmetic operators, you can shorten this type of statement with the `+=` operator. The following statement does the same thing:

>     chars += "R";

There are actually several operations you can perform on strings, including extracting portions of their values and comparing them. You'll look at those in detail in Chapter 4.

Caution
Because addition and concatenation use the same syntax, be sure you know with which data type you are working. For example, if you attempt to add numbers to a non-numeric string, they will be concatenated instead-probably not what you intended.

### Logical Operators

Just as the arithmetic operators work on numeric values, logical operators work with Boolean values. The following logical operators are available:

- `&&` (And) returns true if both of the operands are true.
- `||` (Or) returns true if either of the operands is true.
- `!` (Not) returns the opposite of the variable it prefixes. This takes only one operand, similar to the negation operator for numbers.

The main use for these logical operators is in conditional expressions. You'll learn more about conditionals in Chapter 3.

### Bitwise Operators

Bitwise operators are a category of operators that are used with binary numbers. Each of the operands is converted into a binary number, then manipulated bit by bit. These are mostly useful for manipulating values that have an individual meaning for each bit.

The following bitwise operators are available:

- And (`&`) returns one if both of the corresponding bits are one.
- Or (`|`) returns one if either of the corresponding bits is one.
- Xor (Exclusive Or) (`^`) returns one if either, but not both, of the corresponding bits is one.
- Left shift (`<<`) shifts the bits in the left operand a number of positions specified in the right operand.
- Right shift (`>>`) shifts to the right, including the bit used to store the sign.
- Zero-fill right shift (`>>>`) fills to the right, filling in zeros on the left.

Note
You might think you'll have little use for binary options in JavaScript-and you're right. One area in which they do come in handy is working with color values.

### Comparison Operators

Comparison operators are used to compare two numbers. They return a Boolean value (either true or false) based on whether the operands match the condition. The simplest comparison operator is the equality (`==`) operator; it returns true if the numbers are equal. For example, this expression evaluates to true if `a` has a value of `17`:

>     (a == 17)

Note
Be sure not to confuse the equality operator (`==`) with the assignment operator (`=`). This is one of the most common mistakes in JavaScript programming. You'll learn more about this and other common mistakes in Chapter 14, "Debugging JavaScript Programs."

You can also use the inequality operator (`!=`), which returns true if the numbers are not equal. There are also several other comparison operators to examine the relationship between two values:

- Less than (`<`)
- Greater than (`>`)
- Greater than or equal to (`>=`)
- Less than or equal to (`<=`)

The main use for conditional expressions is in conditional statements, such as the `if` statement. You'll learn about those statements in detail in the next chapter.

### Understanding Operator Precedence

You can use several operators in the same statement. For example, consider the following statement:

>     a = b + x * 25;

As you can see, this statement could mean more than one thing. Should `b` be added to `x` before multiplying by `25`, or after? Will `a` be assigned to `b` or to the entire expression `b + x * 25`? A programming language keeps a set of rules to explain situations like this. These rules are known as operator precedence.

To explain JavaScript's operator precedence, here is a list of all the operators, with the lowest precedence on top. Operators at the bottom of the list are evaluated first, so operators on the bottom are considered more important:

- Comma (`,`), used to separate parameters
- Assignment operator (`=`)
- Conditional operators (`?`, `:`)
- Logical OR (`||`)
- Logical AND (`&&`)
- Bitwise OR (`|`)
- Bitwise XOR (`^`)
- Bitwise AND (`&`)
- Equality (`==`) and inequality (`!=`)
- Comparison operators (`<`, `<=`, `>`, `>=`)
- Bitwise shift (`<<`, `>>`, `>>>`)
- Addition and subtraction (`+`, `-`)
- Multiplication, division, and modulo (`*`, `/`, `%`)
- Negation (`!`, `~`, `-`), increment (`++`), and decrement (`--`)
- Function call or array index (`()`, `[]`)

## Using Variables in Expressions

To explain operators and precedence further, let's look at a few examples using variables and values. First, here's a simple expression:

>     a = b * 5;

There is no confusion about what this statement does; it multiplies `b` by `5`, and stores the result in `a`. Now look at this:

>     a = b * 5 + 1;

This is where operator precedence comes into play. Because multiplication has a higher precedence than addition, `b` is multiplied by `5` before adding `1`.

>     a = b * (5 + 1);

In this case, operator precedence is overridden by the use of parentheses, which have a very high precedence. The numbers `5` and `1` are now added, then `b` is multiplied by the result (6). One more example:

>     a = (b * 5) + 1;

This works exactly like the first example: `b` is multiplied by `5`, then added to `1`. In this particular case, the parentheses don't do anything. I've included this example to make a point: when in doubt, use parentheses. You won't get an error by using unnecessary parentheses, so you can use them whenever you're unsure about precedence, or simply to make your code more readable.

## Converting and Evaluating Variables and Expressions

As discussed earlier, JavaScript is a loosely typed language. You don't need to declare a variable's type when you define it, and you don't need to do anything special to store a different type of data in a variable.

Even in a loosely typed language, there are some cases when you want to convert data to a specific type. You can use several built-in functions of JavaScript, described in the next sections, to handle these conversions.

### The `parseInt` Function

The `parseInt()` function looks for an integer number as the first part of the string. It ignores the decimal portion, if found. For example, this statement assigns the variable `a` to the value `39`:

>     a = parseInt("39 steps");

You can specify an optional second parameter to `parseInt()` that specifies the base of number you're looking for in the string. This can be 8 (octal), 10 (decimal), or 16 (hexadecimal)-in fact, you can use any numeric base. The following statement reads a hexadecimal number from the `text` string variable:

>     a = parseInt(text,16);

`parseInt()` returns a special value, `"NaN"`, (Not a Number) if it encounters a non-numeric character at the beginning of the string. On Windows platforms, zero may be returned instead. See Chapter 14 for specifics about this and other platform-specific issues.

### The `parseFloat` Function

The `parseFloat()` function is similar to `parseInt()`, but works with floating-point values. It attempts to find a decimal floating-point number in the string, and returns it. For example, the following statement assigns the value `2.7178` to the variable `a`:

>     a = "2.7178 is the base of a natural logarithm.";

This statement can handle all the components of a floating-point number: signs, decimal points, and exponents. Like `parseInt()`, if it encounters any other character before it has determined the value, it returns `"NaN"` or zero, depending on the platform.

### The `eval` Function

The `eval()` function has many uses in sophisticated programming techniques, and you'll see it many times throughout this book. Rather than looking for a number in a string, `eval()` looks for any valid JavaScript expression. A simple example assigns `25` to the `a` variable:

>     a = eval("20 + 1 + 4");

The use of `eval()` can be much more complicated than this. You can use any JavaScript expression in the string passed to `eval()`-numeric operations, comparison operations, statements, multiple statements, and even entire JavaScript functions. For example, the following statements define a variable called `Fred` and set its value to `31`. The value of the `text` variable is used as the variable's name:

>     var text = "Fred";
>     var statement = text + "= 31";
>     eval(statement);

Because `eval()` can work with any expression, you can use it to perform calculations based on data entered by the user. You'll use it many times for similar purposes. You can even construct a JavaScript statement or function "on the fly" and execute it. This is one of the most powerful operations available in JavaScript.

Caution
Because `eval()` will execute any statement in the string, be very careful when using it with user-entered strings. A clever user could enter JavaScript statements in the string and cause problems with your program.

## Workshop Wrap-Up

In this chapter, you learned more about the JavaScript language and the basic foundations of JavaScript's structure. You also learned the following concepts:

- The components that make up a JavaScript program or application
- The way JavaScript handles various data types, whether included as a literal value or stored in a variable
- The basics of JavaScript objects and properties
- The techniques for declaring variables, storing data in them, and using them in expressions

### Next Steps

To continue your exploration of the JavaScript language, continue with one of the following chapters:

- To review the basics of JavaScript, see Chapter 1 "Creating Simple JavaScript Programs."
- To learn more about JavaScript's object-oriented features, turn to Chapter 3 " Working with Objects and Events."
- To learn more about the built-in objects and functions in JavaScript, along with custom objects of your own, see Chapter 4, "Using Built-In Objects and Custom Objects."
- To see some applications of the techniques in this chapter, see Chapter 7 "Real-Life Examples I."

### Q&A

Q: | Can I use more than one JavaScript program in the same HTML page?
A: | Yes. Just enclose each program within its own set of `<SCRIPT>` tags. Note that variables you define in one program will be available to others in the same file.
Q: | What is the importance of the `var` keyword? Should I always use it to declare variables?
A: | You only need to use `var` to define a local variable in a function. Outside a function, things work the same whether you use `var` or not.
Q: | In Perl, using the `eval` statement on data entered by the user can be a serious security risk. Is this also true with JavaScript?
A: | Yes and no. Although the user could enter statements and make your program behave strangely, there would be no way to do real damage, because JavaScript has no access to the server. The worst they could do is crash Netscape on their own machine.